export default {
    // 加密
    asencode(str: string, keys: string) {
        const strlen: number = str.length;
        const keyslen: number = keys.length;
        let newstr: string = '';
        for (let i = 0; i < strlen; i++) {
            const rnum: number = Math.round(Math.random() * 1000) % keyslen;
            const rnumx: number = Number(rnum.toString().slice(-1)) + 1;
            const ylen: number = keyslen - rnumx;
            let tmpnum = str.codePointAt(i) as number;
            const y1: number = tmpnum % ylen;
            tmpnum = (tmpnum - y1) / ylen;
            const y2: number = tmpnum % ylen;
            tmpnum = (tmpnum - y2) / ylen;
            newstr +=
                keys[(tmpnum % ylen) + rnumx] +
                keys[y2 + rnumx] +
                keys[y1 + rnumx] +
                keys.charAt(rnum);
        }
        return newstr;
    },

    // 解密
    asdecode(str: string, keys: string) {
        try {
            const strlen: number = str.length;
            const keyslen: number = keys.length;
            let newstr: string = '';
            for (let i = 0; i < strlen; i++) {
                const rnum: number = keys.indexOf(str[i + 3]);
                const rnumx: number = Number(rnum.toString().slice(-1)) + 1;
                const ylen: number = keyslen - rnumx;
                newstr += String?.fromCodePoint(
                    (keys.indexOf(str[i++]) - rnumx) * ylen * ylen +
                        (keys.indexOf(str[i++]) - rnumx) * ylen +
                        (keys.indexOf(str[i++]) - rnumx)
                );
            }
            return newstr;
        } catch (error) {
            return '';
        }
    },
    getCodeData(data: any, keys: string) {
        try {
            data = JSON.parse(data);
            // console.log(666.777888, this.asdecode(data.code, keys),'1111111', data, keys);
            return JSON.parse(
                this.asdecode(data.data, this.asdecode(data.code, keys))
            );
        } catch (error) {
            return;
        }
    },
    sendCodeData(data: any, keys: string, code: string) {
        // console.log(666.300006,data,this.asdecode(code, keys))
        return {
            code: code,
            data: this.asencode(
                JSON.stringify(data),
                this.asdecode(code, keys)
            ),
        };
    },
    // 打乱字符
    asnewkey(str: string) {
        const newarr: string[] = [];
        str.split('').forEach((el: string) => {
            newarr.splice(Math.round(Math.random() * newarr.length), 0, el);
        });
        // console.log(666.1002,newarr.length,newarr)
        return newarr.join('');
    },
};
